package cn.iocoder.yudao.module.contract.controller.admin.exportContract;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.contract.controller.admin.exportContract.vo.ExportContractGenerateVO;
import cn.iocoder.yudao.module.contract.controller.admin.exportContract.vo.ExportOrderExportVO;
import cn.iocoder.yudao.module.contract.controller.admin.exportContract.vo.ExportOrderPageReqVO;
import cn.iocoder.yudao.module.contract.controller.admin.exportContract.vo.ExportOrderRespVO;
import cn.iocoder.yudao.module.contract.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.client.ClientDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.exportContract.ExportContractDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.invoice.InvoiceDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.invoiceContract.InvoiceContractDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDetailsDO;
import cn.iocoder.yudao.module.contract.dal.mysql.order.OrderDetailsMapper;
import cn.iocoder.yudao.module.contract.service.client.ClientService;
import cn.iocoder.yudao.module.contract.service.company.CompanyService;
import cn.iocoder.yudao.module.contract.service.exportContract.ExportContractService;
import cn.iocoder.yudao.module.contract.service.order.OrderService;
import cn.iocoder.yudao.module.contract.webservice.ContractWebService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 出口订单")
@RestController
@RequestMapping("/contract/export/order")
@Validated
public class ExportOrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderDetailsMapper orderDetailsMapper;
    @Resource
    private ExportContractService exportContractService;
    @Resource
    private CompanyService companyService;
    @Resource
    private ClientService clientService;
    @Resource
    private ContractWebService contractWebService;

    @GetMapping("/get")
    @Operation(summary = "获得订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<?> getOrder(@RequestParam("id") Long id) {
        OrderDO order = orderService.getOrder(id);
        List<OrderDetailsDO> detailsList = orderService.getOrderDetailsListByOrderId(order.getId());
        Map<String,Object> result = new HashMap<>();
        result.put("order",order);
        result.put("detailsList",detailsList);
        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得订单分页")
    public CommonResult<PageResult<ExportOrderRespVO>> getOrderPage(@Valid ExportOrderPageReqVO pageReqVO) {
        PageResult<OrderDO> pageResult = orderService.getExportOrderPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ExportOrderRespVO.class));
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出订单 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportOrderExcel(@Valid ExportOrderPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OrderDO> list = orderService.getExportOrderPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "订单.xls", "数据", ExportOrderExportVO.class,
                BeanUtils.toBean(list, ExportOrderExportVO.class));
    }

    @GetMapping("/getOrdersDetails")
    @Operation(summary = "获得订单")
    @Parameter(name = "ids", description = "编号", required = true, example = "1024")
    public CommonResult<?> getOrdersDetails(@RequestParam("orderIds") String orderIds) {
        String [] ids = orderIds.split(",");
        List<OrderDO> orderList = orderService.list(Wrappers.<OrderDO>lambdaQuery().in(OrderDO::getId, Arrays.asList(ids)));
        if(orderList.size()==0){
           return error("订单数据不存在");
        }
        if(ids.length!=orderList.size()){
            return error("订单数据异常");
        }
        Map<String, List<OrderDO>> ordersMap = orderList.stream().collect(Collectors.groupingBy(item -> item.getBukrs() + "-" + item.getKunnr()+ "-" +item.getInco1()+ "-" +item.getInco2()));
        if(ordersMap.size()>1){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"请选择售达方、公司主体、国际贸易条件相同的订单数据");
        }
        OrderDO order = orderList.stream().min(Comparator.comparing(OrderDO::getAudat).thenComparing(OrderDO::getVbeln)).get();
        CompanyDO companyDO = companyService.getOne(Wrappers.<CompanyDO>lambdaQuery().eq(CompanyDO::getCompanyCode,order.getBukrs()));
        if(companyDO==null || StringUtils.isBlank(companyDO.getEnAddress()) || StringUtils.isBlank(companyDO.getEnName())){
            return error("公司不存在或公司英文地址公司英文名称为空");
        }
        ClientDO clientDO = clientService.getOne(Wrappers.<ClientDO>lambdaQuery().eq(ClientDO::getClientCode,order.getKunnr()));
        if(clientDO==null || StringUtils.isBlank(clientDO.getStreet())){
            return error("客户不存在或客户地址为空");
        }
        if(StringUtils.isBlank(order.getBstnk())){
            return error("合同号码不能为空");
        }
        List<OrderDetailsDO> detailsList = orderDetailsMapper.selectList(Wrappers.<OrderDetailsDO>lambdaQuery().in(OrderDetailsDO::getOrderId,Arrays.asList(ids)).orderByAsc(OrderDetailsDO::getVbeln,OrderDetailsDO::getPosnr).orderByAsc(OrderDetailsDO::getVbeln,OrderDetailsDO::getPosnr));
        order.setId(null);
        order.setCreator(null);
        order.setCreateTime(null);
        order.setUpdater(null);
        order.setUpdateTime(null);
        ExportContractDO exportContract = BeanUtils.toBean(order,ExportContractDO.class);
        exportContract.setButxt(companyDO.getEnName());
        Map<String,Object> result = new HashMap<>();
        result.put("orderIds",orderIds);
        result.put("companyEnAddress",companyDO.getEnAddress());
        result.put("collectionAddress",clientDO.getStreet());
        result.put("exportContract",exportContract);
        result.put("detailsList",detailsList);
        return success(result);
    }

    @PostMapping("/generateContract")
    @Operation(summary = "合同生成")
    public CommonResult<Boolean> generateContract(@RequestBody ExportContractGenerateVO exportContractGenerate) {
        exportContractService.exportContractService(exportContractGenerate);
        ExportContractDO exportContract = exportContractGenerate.getExportContract();
        if("2".equals(exportContract.getStatus())){
            List<OrderDO> orderList = orderService.list(Wrappers.<OrderDO>lambdaQuery().eq(OrderDO::getContractNo,exportContract.getBstnk()) );
            for(OrderDO orderDO : orderList){
                //合同生成 2
                contractWebService.pushOrderStatus(orderDO.getVbeln(),exportContract);
                if(!"1".equals(exportContract.getIsPushRelease())){
                    break;
                }
            }
        }
        exportContractService.updateById(exportContract);
        return success(true);
    }
}
